package com.example.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.common.Result;
import com.example.entity.Account;
import com.example.entity.Admin;
import com.example.entity.store;
import com.example.service.impl.AdminServiceImpl;
import com.example.service.storeService;
import com.example.utils.TokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/store")
public class storeController {

    @Autowired
    private storeService storeService;

    @Autowired
    AdminServiceImpl adminServiceImpl;

    @GetMapping("/list")
    public Result list(@RequestParam("pageNo") int pageNo,@RequestParam("pageSize") int pageSize,@RequestParam(required = false)String name ){
        Account currentUser = TokenUtils.getCurrentUser();
        Integer id = currentUser.getId();
        Page<store> page = storeService.page(new Page<store>(pageNo, pageSize), new QueryWrapper<store>().eq("business",id).like(name != null,"name",name));
        for (store record : page.getRecords()) {
            Admin admin = adminServiceImpl.selectById(Integer.valueOf(record.getBusiness()));
            record.setBusiness(admin.getName());
        }
        return Result.success(page);
    }

    @PostMapping("/add")
    public Result add(@RequestBody store store){
        Account currentUser = TokenUtils.getCurrentUser();
        Integer id = currentUser.getId();
        store.setBusiness(String.valueOf(id));
        store.setCreateTime(new Date());
        List<Integer> goodList = store.getGoodList();
        String goods = "";
        for (Integer integer : goodList) {
            goods += integer.toString()+",";
        }
        store.setGoods(goods.substring(0,goods.length()-1));
        storeService.save(store);
        return Result.success();
    }

    @PutMapping("/edit")
    public Result edit(@RequestBody store store){
        UpdateWrapper<store> updateWrapper = new UpdateWrapper<>();
        List<Integer> goodList = store.getGoodList();
        String goods = "";
        for (Integer integer : goodList) {
            goods += integer.toString()+",";
        }
        store.setGoods(goods.substring(0,goods.length()-1));

        updateWrapper.set("name",store.getName());
        updateWrapper.set("goods",store.getGoods());
        updateWrapper.set("address",store.getAddress());
        updateWrapper.eq("id",store.getId());
        storeService.update(updateWrapper);
        return Result.success();
    }

    @DeleteMapping("/remove/{id}")
    public Result removeByid(@PathVariable int id){
        storeService.removeById(id);
        return Result.success();
    }

}
